package ventanas;

import isi_graf.isi_DualFinanceChart;
import isi_ib.MyContract;
import isi_ib.MyOrder;
import isi_ib.barra_trade;
import isi_ib.barras_trade;
import isi_ib.historico_ib;
import isi_ib.isi_estudios;
import isi_ib.reltime_bars_ib;

import java.awt.EventQueue;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import java.awt.BorderLayout;
import javax.swing.JButton;

import com.ib.client.Contract;
import com.ib.client.ContractDetails;
import com.ib.client.EClientSocket;
import com.ib.client.EWrapper;
import com.ib.client.Execution;
import com.ib.client.Order;
import com.ib.client.OrderState;
import com.ib.client.UnderComp;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.SwingConstants;
import javax.swing.JTextField;

import org.jfree.chart.ChartPanel;

import utiles_isi.isi_conexion;

public class ISI_TRADING implements EWrapper{
    
	public int nextOrderID;
	private JFrame frame;
	private JButton btnConecta;
	private Alerta vAlerta;
	isi_conexion conexion_;
	
	
	private historico_ib historico;
	private Vhistorico vhistorico;
	
	//////////////////////
	private EClientSocket   m_client;
	private boolean m_disconnectInProgress;
	private Vcontrato vcontrato;
	private MyContract ccontrato;
	private barras_trade barras ;
	private MyOrder myorder;
	private isi_estudios estudio;
	private isi_DualFinanceChart dualtimechart;
	//Realtime 
	reltime_bars_ib realbars;
	private JTextField validOrderID;
	
	
	/////////////////////
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ISI_TRADING window = new ISI_TRADING();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ISI_TRADING() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		
		
		
		frame = new JFrame();
		frame.getContentPane().setForeground(new Color(0, 100, 0));
		frame.setBounds(100, 100, 881, 154);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		
		/* * mis news Declaraciones */
		m_client = new EClientSocket(this);
		ccontrato=new MyContract("","");
		historico=new historico_ib();
		myorder= new MyOrder(-1,ccontrato);
		myorder.setConexion(conexion_);
		try {ccontrato.Carga("ES");} catch (Exception e) {e.printStackTrace();}
		vAlerta = new Alerta();
		barras = new barras_trade();
		//realbars= new reltime_bars_ib() ;
		//realbars.setContract(ccontrato.contrato);
		//realbars.setClientSocket(m_client);
		realbars=new reltime_bars_ib(0, ccontrato.contrato,5,m_client,300);
		
		
		// inicio de variables
		vcontrato=null;
		vhistorico=null;
		m_disconnectInProgress=false;
		vAlerta.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		nextOrderID=-1;
		
		
		/* * */
		frame.getContentPane().setLayout(null);
		
		JToolBar toolBar = new JToolBar();
		toolBar.setBounds(0, 0, 873, 23);
		frame.getContentPane().add(toolBar);
		
		btnConecta = new JButton("Desconectado");
		btnConecta.setForeground(new Color(165, 42, 42));
		
		btnConecta.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ConectaIB();
			}
		});
		toolBar.add(btnConecta);
		
		JButton btnContrato = new JButton("Contrato");
		btnContrato.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ventanaContrato();
			}
		});
		toolBar.add(btnContrato);
		
		JButton btnLog = new JButton("Log");
		btnLog.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				vAlerta.anadeMensaje(ccontrato.toString());
				vAlerta.setVisible(true);
			}
		});
		
		JButton btnHistorico = new JButton("Historico");
		btnHistorico.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ventanaHistorico();
			}
		});
		toolBar.add(btnHistorico);
		
		JButton btnGrafico = new JButton("Estudios");
		btnGrafico.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//realbars.setContract(ccontrato.contrato);
				//realbars.setClientSocket(m_client);
				Config_graf frame = new Config_graf(historico,ccontrato,realbars);
				frame.setVisible(true);
				frame.setAlerta(vAlerta);
				
			}
		});
		toolBar.add(btnGrafico);
		
		JButton button = new JButton("$$$$");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//realbars.setContract(ccontrato.contrato);
				
				realbars.iniciaRealtimebars(null);
				estudio = new isi_estudios(null,null,"",false);
				estudio.Carga();
				
				dualtimechart= new isi_DualFinanceChart("F - Hoy","values",0);
				ChartPanel panel2=dualtimechart.CreaChart();
				dualtimechart.Inicia(estudio,null,null,0);
				Grafico frame2 = new Grafico(panel2);
				frame2.setVisible(true);
				
				dualtimechart.Visibilidad(true,true,true,false,true,false,true,false,false,false,false,false);
				m_client.reqAutoOpenOrders(true);
				
				
			}
		});
		toolBar.add(button);
		
		JButton btnCompra = new JButton("Compra");
		btnCompra.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Compra();
			}
		});
		toolBar.add(btnCompra);
		
		JButton btnCancela = new JButton("Cancela");
		btnCancela.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//m_client.cancelOrder(5655442);
				myorder.Cancel(m_client);
				
			}
		});
		
		JButton btnVende = new JButton("Vende");
		btnVende.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Vende();
			}
		});
		toolBar.add(btnVende);
		toolBar.add(btnCancela);
		btnLog.setHorizontalAlignment(SwingConstants.RIGHT);
		toolBar.add(btnLog);
		
		JButton button_1 = new JButton("Req OpenOrders");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				m_client.reqAllOpenOrders();
			}
		});
		button_1.setHorizontalAlignment(SwingConstants.RIGHT);
		toolBar.add(button_1);
		
		validOrderID = new JTextField();
		validOrderID.setBackground(Color.GRAY);
		toolBar.add(validOrderID);
		validOrderID.setColumns(10);
		
		
	}
	
	/////////////// ORDERS
	private void Compra(){
	       
	   	myorder.SetOrderId(nextOrderID);
		myorder.CompraMercado(1);
		myorder.Open(m_client);
		myorder.reqIDs(m_client); // pide un nuevo id llega en nextValidID
	
	}
	private void Vende(){
	   	myorder.SetOrderId(nextOrderID);
		myorder.VendeMercado(1);
		myorder.Open(m_client);
		myorder.reqIDs(m_client);
		
	}
	
	///////////////////////////////////////////// MIS FUNCIONES
	private void setImagenConectado(){
		if (m_client.isConnected()){
       	 btnConecta.setText("Conectado");
       	 btnConecta.setForeground(new Color(0, 128, 128));
        }
        else {
       	 btnConecta.setText("Desconectado");
       	 btnConecta.setForeground(new Color(165, 42, 42));
        }
		
	}
	private void ConectaIB(){
		 m_disconnectInProgress = false;
		 if (m_client.isConnected()){
			 m_disconnectInProgress = true;
			 m_client.eDisconnect();
		    }
	     else m_client.eConnect( "", 7496, 0); 
		 setImagenConectado();
         
	}
	private void ventanaContrato(){
		try {
			if(vcontrato==null)	vcontrato = new Vcontrato(ccontrato);
			vcontrato.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			vcontrato.setVisible(true);
			vcontrato.RecogeValores();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void ventanaHistorico(){
		 
		try {
			if(vhistorico==null)	
				vhistorico = new Vhistorico(historico,ccontrato.contrato, m_client,vAlerta);
			vhistorico.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			vhistorico.setVisible(true);
			//vcontrato.RecogeValores();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	///////////////////////////////////////////// MIS FUNCIONES
	@Override
	public void error(Exception e) {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("Errot Excepcion"+e.getMessage());
		
	}

	@Override
	public void error(String str) {
		vAlerta.anadeMensaje("Error: "+str);
		
	}

	@Override
	public void error(int id, int errorCode, String errorMsg) {
		vAlerta.anadeMensaje("Error ID:"+errorMsg);
		
	}

	@Override
	public void connectionClosed() {
		vAlerta.anadeMensaje("Disconnected to Tws server version " + m_client.serverVersion() + " at " +  m_client.TwsConnectionTime());
		
	}

	@Override
	public void tickPrice(int tickerId, int field, double price,
			int canAutoExecute) {
		vAlerta.anadeMensaje("--- tickPrice ---");
		
	}

	@Override
	public void tickSize(int tickerId, int field, int size) {
		vAlerta.anadeMensaje("--- tickSize ---");
		
	}

	@Override
	public void tickOptionComputation(int tickerId, int field,
			double impliedVol, double delta, double optPrice,
			double pvDividend, double gamma, double vega, double theta,
			double undPrice) {
		vAlerta.anadeMensaje("--- tickOptionComputation ---");
		
	}

	@Override
	public void tickGeneric(int tickerId, int tickType, double value) {
		vAlerta.anadeMensaje("--- tickGeneric ---");
		
	}

	@Override
	public void tickString(int tickerId, int tickType, String value) {
		vAlerta.anadeMensaje("--- tickString ---");
		
	}

	@Override
	public void tickEFP(int tickerId, int tickType, double basisPoints,
			String formattedBasisPoints, double impliedFuture, int holdDays,
			String futureExpiry, double dividendImpact, double dividendsToExpiry) {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("--- tickEFP ---");
		
	}

	@Override
	public void orderStatus(int orderId, String status, int filled,
			int remaining, double avgFillPrice, int permId, int parentId,
			double lastFillPrice, int clientId, String whyHeld) {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("orderStatus: "+String.valueOf(orderId)+"--->"+status);
		myorder.GuardaStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld);
		
		
	}

	@Override
	public void openOrder(int orderId, Contract contract, Order order,
			OrderState orderState) {
		// TODO Auto-generated method stub
		
		vAlerta.anadeMensaje("openOrder "+String.valueOf(orderId)+"--->"+orderState.m_status);
		myorder.GuardaOrderState(orderId, orderState);
		myorder.GuardaOrder(order, contract, true);
		
		
	}

	@Override
	public void openOrderEnd() {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("openOrder END ");
		
	}

	@Override
	public void updateAccountValue(String key, String value, String currency,
			String accountName) {
		vAlerta.anadeMensaje("--- updateAccountValue ---");
		
	}

	@Override
	public void updatePortfolio(Contract contract, int position,
			double marketPrice, double marketValue, double averageCost,
			double unrealizedPNL, double realizedPNL, String accountName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAccountTime(String timeStamp) {
		vAlerta.anadeMensaje("--- updateAccountTime ---");
		
	}

	@Override
	public void accountDownloadEnd(String accountName) {
		vAlerta.anadeMensaje("--- accountDownloadEnd ---");
		
	}

	@Override
	public void nextValidId(int orderId) {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("nextValidId: "+String.valueOf(orderId));
		validOrderID.setText(String.valueOf(orderId));
		nextOrderID=orderId;
		
	}

	@Override
	public void contractDetails(int reqId, ContractDetails contractDetails) {
		vAlerta.anadeMensaje("--- contractDetails ---");
		
	}

	@Override
	public void bondContractDetails(int reqId, ContractDetails contractDetails) {
		vAlerta.anadeMensaje("--- bondContractDetails ---");
		
	}

	@Override
	public void contractDetailsEnd(int reqId) {
		vAlerta.anadeMensaje("--- contractDetailsEnd ---");
		
	}

	@Override
	public void execDetails(int reqId, Contract contract, Execution execution) {
		vAlerta.anadeMensaje("--- execDetails ---");
		
	}

	@Override
	public void execDetailsEnd(int reqId) {
		vAlerta.anadeMensaje("--- execDetailsEnd ---");
		
	}

	@Override
	public void updateMktDepth(int tickerId, int position, int operation,
			int side, double price, int size) {
		vAlerta.anadeMensaje("--- updateMktDepth ---");
		
	}

	@Override
	public void updateMktDepthL2(int tickerId, int position,
			String marketMaker, int operation, int side, double price, int size) {
		vAlerta.anadeMensaje("--- updateMktDepthL2 ---");
		
	}

	@Override
	public void updateNewsBulletin(int msgId, int msgType, String message,
			String origExchange) {
		vAlerta.anadeMensaje("--- updateNewsBulletin ---");
		
	}

	@Override
	public void managedAccounts(String accountsList) {
		vAlerta.anadeMensaje("--- managedAccounts ---");
		
	}

	@Override
	public void receiveFA(int faDataType, String xml) {
		vAlerta.anadeMensaje("--- receiveFA ---");
		
	}

	@Override
	public void historicalData(int reqId, String date, double open,
			double high, double low, double close, int volume, int count,
			double WAP, boolean hasGaps) {
		
		barra_trade bara = new barra_trade(reqId,date,open,high,low,close,volume,count,WAP,hasGaps);
		barras.add(bara);
		barras.anadeBarraSQL(bara);
		vAlerta.anadeMensaje(bara.toString());
		
	}

	@Override
	public void scannerParameters(String xml) {
		vAlerta.anadeMensaje("--- scannerParameters ---");
		
	}

	@Override
	public void scannerData(int reqId, int rank,
			ContractDetails contractDetails, String distance, String benchmark,
			String projection, String legsStr) {
		vAlerta.anadeMensaje("--- scannerData ---");
		
	}

	@Override
	public void scannerDataEnd(int reqId) {
		vAlerta.anadeMensaje("--- scannerDataEnd ---");
		
	}

	@Override
	public void realtimeBar(int reqId, long time, double open, double high,
			double low, double close, long volume, double wap, int count) {
		// TODO Auto-generated method stub
		
		int accion_=0;
		barra_trade barra1_ = new barra_trade(reqId,String.valueOf(time),open,high,low,close,volume,count,wap,false);
		realbars.Add(barra1_);
		
		if(estudio.Add(barra1_))
		{
			if(dualtimechart!=null)
			dualtimechart.Visibilidad(true,true,true,false,true,false,true,false,false,false,false,false);
			
			accion_=estudio.compra_vende();
			if(accion_>0) vAlerta.anadeMensaje("------------>COMPRA<--->: "+String.valueOf(close));
			else
			if(accion_<0) vAlerta.anadeMensaje("------------>VENDE<---->: "+String.valueOf(close));
		}
				
	//	vAlerta.anadeMensaje(barra1_.toString());
		//anadeMensaje(bara.toString());		
	//	if (acumulado.add(bara)) {
	//		if (dualtimechart!=null) dualtimechart.Add(bara);
		//}
		//barras.anadeBarraSQLReal(bara);
		
	}

	@Override
	public void currentTime(long time) {
		vAlerta.anadeMensaje("--- currentTime ---");
		
	}

	@Override
	public void fundamentalData(int reqId, String data) {
		vAlerta.anadeMensaje("--- fundamentalData ---");
		
	}

	@Override
	public void deltaNeutralValidation(int reqId, UnderComp underComp) {
		 vAlerta.anadeMensaje("--- deltaNeutralValidation ---");
		
	}

	@Override
	public void tickSnapshotEnd(int reqId) {
		 vAlerta.anadeMensaje("--- tickSnapshotEnd ---");
		
	}

	@Override
	public void marketDataType(int reqId, int marketDataType) {
		// TODO Auto-generated method stub
		vAlerta.anadeMensaje("--- marketDataType ---");
		
	}
}
